<?php

namespace app\admin\controller;

use app\common\controller\Common;
use think\facade\Db;
use think\facade\Cookie;
use think\facade\View;
use think\facade\Config;
use think\facade\Request as req;
use PhpZip\ZipFile;

class Index extends Common
{
    const apiurl = 'https://kefu.69kz.com/';
    /**
     * 客服后台主页
     */
    public function index()
    {
        $where = [
            ['main_id', '=', $this->main_id]
        ];
        $data = Db::name('im_site_data')->where($where)->find();
        // 未接待会员
        $stat_wjd = 0;
        foreach (Cookie::get() as $key=>$item) {
            if (strpos($key, 'unread_list_number_') !== false && $item != 0) {
                $stat_wjd++;
            }
        }
        $data['im_stat_wjd'] = $stat_wjd;
        // 今日聊天数
        $data['im_stat_jrlt'] = Db::name('im_record')
            ->where($where) ->whereDay('send_time')->count();
        // 今日评价数量
        $data['im_stat_jrpj'] = Db::name('im_evaluation')
            ->where($where) ->whereDay('add_time')->count();
        // 聊天消息总数
        $data['im_stat_ltxx'] = Db::name('im_record')
            ->where($where)->count();
        // 总评价数量
        $data['im_stat_zpj']  = Db::name('im_evaluation')
            ->where($where)->count();
        // 公告
        $host = self::apiurl.'api.php/notice';
        $arr = [];
        $header = array('HTTP/1.1 200 OK');
        $return = curlPost($host, $arr, 5, $header, 'array');
        $res = (array)json_decode($return);
        $data['notice'] = $res['data']->notice;
        // 最新版本
        $ghost = self::apiurl.'api.php/grade';
        $garr = ['now_grade' => Config::get('website.version')];
        $gheader = array('HTTP/1.1 200 OK');
        $greturn = curlPost($ghost, $garr, 5, $gheader, 'array');
        $gres = (array)json_decode($greturn);
        if($gres['code'] == 200){
            $key = array_search(max($gres['data']),$gres['data']);
            $detail = [];
            foreach ($gres['data'] as $k => $v){
                $detail[] = '版本：【'.$v->edition.'】<br><br>'.$v->detail_content.'<br>';
            }
            $data['grade'] = $gres['data'][$key]->edition;
            $data['detail'] = implode($detail);
            $data['up'] = "<img src='/static/admin/images/warning.gif' class='eimg'/><button class='edition' onclick='upgrade()'>升级版本</button><button class='edetail' onclick='newd()'>版本详情</button>";
        }else{
            $data['grade'] = $gres['msg'];
            $data['detail'] = '';
            $data['up'] = '';
        }
        // 授权
        $sqhost = self::apiurl.'api.php/dcurl';
        $sqarr = ['realname' => $_SERVER['HTTP_HOST']];
        $sqheader = array('HTTP/1.1 200 OK');
        $sqreturn = curlPost($sqhost, $sqarr, 5, $sqheader, 'array');
        $sqres = (array)json_decode($sqreturn);
        if($sqres['code'] == 200){
            $data['auth_url'] = '<div style="text-align:center;margin:10px 0px 30px 0px;background:green;height:100%;line-height:50px;color:white;">恭喜您，此域名已授权！使用酷站PHP客服系统请遵守国家法律法规使用，禁止使用违法用途否则一切后果自负。</div>'; 
        }else{
            $data['auth_url'] = '<div style="text-align:center;margin:10px 0px 30px 0px;background:red;height:100%;line-height:50px;color:white;">'.$sqres['msg'].'</div>'; 
        }
        View::assign($data);
        return view();
    }
    // 升级客服系统
    public function upup(){
        if(req::has('edition')){
            if(req::post('edition') != Config::get('website.version'))
                return json(['code' => 300, 'data' => '当前版本号不符']);
            $ghost = self::apiurl.'api.php/grade';
            $garr = ['now_grade' => Config::get('website.version')];
            $gheader = array('HTTP/1.1 200 OK');
            $greturn = curlPost($ghost, $garr, 5, $gheader, 'array');
            $gres = (array)json_decode($greturn);
            if($gres['code'] != 200)
                return json(['code' => 300, 'data' => $gres['msg']]);
            $dir = root_path() . 'runtime' . DIRECTORY_SEPARATOR . 'grade' . DIRECTORY_SEPARATOR;
            if (!is_dir($dir)) {
                @mkdir($dir, 0755, true);
            }
            foreach ($gres['data'] as $k => $v){// 多版本依次更新
                $file = file_get_contents(self::apiurl.$v->down_url);
                $pic_local_path = $dir.date('Ymd', time());
                if(file_exists($pic_local_path.'/'.$v->edition)){
                    self::deldir($pic_local_path.'/'.$v->edition.'/');
                }
                $pic_local = $pic_local_path . '/'.md5(time()).'.zip';
                if (!file_exists($pic_local_path)) {
                    mkdir($pic_local_path, 0777, true);
                    @chmod($pic_local_path, 0777);
                }
                file_put_contents($pic_local, $file);
                if (!file_exists($pic_local)) {
                    return json(['code' => 300, 'data' => '没有文件上传或服务器上传限制超过【问题版本：'.$v->edition.'】']);
                }
                $tmpFile = $pic_local;
                $info = [];
                $zip = new ZipFile();
                try {
                    // 打开系统压缩包
                    try {
                        $zip->openFile($tmpFile);
                    } catch (ZipException $e) {
                        @unlink($tmpFile);
                        return json(['code' => 300, 'data' => '无法打开压缩文件【问题版本：'.$v->edition.'】']);
                    }
                    try {
                        $zip->extractTo($pic_local_path);
                    } catch (ZipException $e) {
                        @unlink($tmpFile);
                        return json(['code' => 300, 'data' => '无法提取文件【问题版本：'.$v->edition.'】']);
                    }
                    if(!file_exists($pic_local_path.'/'.$v->edition))
                        return json(['code' => 300, 'data' => '升级包无法获取【问题版本：'.$v->edition.'】']);
                    foreach (self::getCheckDirs() as $k => $dir) {
                        if (is_dir($pic_local_path.'/'.$v->edition.'/'.$dir)) {
                            copydirs($pic_local_path.'/'.$v->edition.'/'.$dir, root_path());
                        }
                    }
                    $sqlfile = root_path().'public/mysql';
                    if (!file_exists($sqlfile)) {
                        mkdir($sqlfile, 0777, true);
                        @chmod($sqlfile, 0777);
                    }
                    $res = self::upgradefile(['version'=>$v->edition]);
                    if(!$res)
                        return json(['code' => 300, 'data' => '升级失败，请联系官方人员【问题版本：'.$v->edition.'】']);
                } catch (AddonException $e) {
                    return json(['code' => 300, 'data' => $e->getMessage()]);
                } catch (Exception $e) {
                    return json(['code' => 300, 'data' => $e->getMessage()]);
                } finally {
                    $zip->close();
                    @unlink($tmpFile);
                    if(file_exists($pic_local_path.'/'.$v->edition)){
                        self::deldir($pic_local_path.'/'.$v->edition.'/');
                    }
                }
            }
            // 数据库操作
            foreach ($gres['data'] as $kk => $vv){
                $ssqlfile = root_path().'public/mysql';
                $ssqlurl = $ssqlfile.'/'.$vv->edition .'.php';
                if(file_exists($ssqlurl)){// 数据库操作
                    $sqhost = $ssqlfile.'/'.$vv->edition .'.php';
                    $sres = self::database_operation($sqhost);
                    if($sres == 400)
                        return json(['code' => 300, 'data' => '版本升级成功！数据库升级失败【问题版本：'.$vv->edition.'】']);
                }
            }
            return json(['code' => 200, 'data' => '恭喜您！版本升级成功！']);
        }else{
            return json(['code' => 300, 'data' => '缺少参数']);
        }
    }
    // 数据库操作
    public function database_operation($file)
    {
        $db = Config::get('database.connections.mysql');
        $sql = file_get_contents($file);
        $ssql = str_replace("__PREFIX__", $db['prefix'], $sql);
        foreach (explode(';', $ssql) as $k => $v){
            if($v != '')
                $a = Db::execute($v);
            if($a != 1 && $a != 0){
                return 400;
            }
        }
        return 200;
    }
    //
    protected static function getCheckDirs()
    {
        return [
            Config::get('website.file_dir')
        ];
    }
    // 递归删除目录
    public function deldir($path){
        //如果是目录则继续
        if(is_dir($path)){
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            //如果 $p 中有两个以上的元素则说明当前 $path 不为空
            if(count($p)>2){
                foreach($p as $val){
                    //排除目录中的.和..
                    if($val !="." && $val !=".."){
                        //如果是目录则递归子目录，继续操作
                        if(is_dir($path.$val)){
                            //子目录中操作删除文件夹和文件
                            self::deldir($path.$val.'/');
                        }else{
                            //如果是文件直接删除
                            unlink($path.$val);
                        }
                    }
                }
            }
        }
        //删除目录
        return rmdir($path);
    }
    // 替换升级包版本
    public function upgradefile($arr)
    {
        $upgrade=Config::get('website');
        $upgrade=array_merge($upgrade,$arr);
        file_put_contents(config_path() . '/'. 'website.php','<?php' . "\n\nreturn " . var_export($upgrade, true) . ";");
        return true;
    }
}